<template>
  <form-dialog
    :visible="visible"
    :loading="loading"
    @handleClose="handleClose"
    :title="title">
    <template slot="content">
      <p>{{$t('desktopManage.message.selectUSBRule')}}</p>
      <el-select filterable v-model="value">
        <el-option
          v-for="(item, index) in options"
          :key="index"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
    </template>
    <template slot="footer">
      <el-button @click="handleClose">{{$t('common.cancel')}}</el-button>
      <el-button :disabled="loading" type="primary" @click="submit">{{$t('common.confirm')}}</el-button>
    </template>
  </form-dialog>
</template>
<script lang="ts">
import Vue from 'vue'
import FormDialog from '../../../components/Dialog/formDialog.vue'
export default Vue.extend({
  components: {
    FormDialog
  },
  data() {
    return {
      title: '',
      visible: false,
      loading: false,
      data: {},
      options: [],
        value: ''
    }
  },
  methods: {
    handleClose () {
      this.visible = false;
      this.loading = false;
    },
    submit () {
      this.loading = true;
      if (this.value) {
        let promiseArray: any = [];
        if (Array.isArray(this.data)) {
          this.data.forEach((item: any) => {
            promiseArray.push((this as any).$pandaApi.patchDesktops(item.desktop_pool, item.id, { usb_rule_group: this.value }));
          })
        } else {
          promiseArray.push((this as any).$pandaApi.patchDesktops((this.data as any).desktop_pool, (this.data as any).id, { usb_rule_group: this.value }))
        }
        Promise.all(promiseArray).then((res: any) => {
          this.loading = false;
          this.visible = false;
          this.$emit('success');
          this.$message({
            message: this.$t('desktopManage.message.operationSuccess', {operation: this.title}).toString(),
            type: 'success'
          });
        }).catch(() => {
          this.loading = false;
          this.$message({
            message: this.$t('desktopManage.message.operationFail', {operation: this.title}).toString(),
            type: 'warning'
          });
        })
      }
    },
    init (obj: any) {
      this.value = '';
      this.data = {};
      this.options = obj.options;
      this.data = obj.data;
      this.title = this.$t('desktopManage.operation.setUSBRule').toString();
      // console.log(obj);
      if (obj.data.usb_rule_group) {
        this.value = obj.data.usb_rule_group;
      } else {
        obj.options.forEach((item: any) => {
          if (item.name === this.$t('policy.DefaultUSBRuleGroup')) {
            this.value = item.id;
          }
        })
      }
      this.visible = true;
    }
  }
})
</script>

<style lang="sass" scoped>

</style>
